package com.carlton.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.carlton.common.Result;
import com.carlton.common.Status;
import com.carlton.exception.LeafServerException;
import com.carlton.service.SnowflakeApiService;
import com.carlton.service.SnowflakeService;

@Service
public class SnowflakeServiceImpl implements SnowflakeService {

	public static Logger logger = LoggerFactory.getLogger(SnowflakeServiceImpl.class);

	@Autowired
	private SnowflakeApiService snowflakeApiService;

	@Override
	public Long obtainId() {
		logger.info("获取ID");
		Result result = snowflakeApiService.getId(null);
		return get(result);
	}

	@Override
	public List<Long> batchObtainId(Integer max) {
		logger.info("批量获取ID入参{}", max);
		List<Result> resultList = snowflakeApiService.batchResult(max >= 100 ? 100 : max);
		return batchGet(resultList);
	}

	/**
	 * 获取ID
	 *
	 * @param result
	 * @return
	 */
	private Long get(Result result) {
		if (result.getStatus().equals(Status.EXCEPTION)) {
			throw new LeafServerException(result.toString());
		}
		return Long.valueOf(result.getId());
	}

	/**
	 * 获取ID列表
	 *
	 * @param resultList
	 * @return
	 */
	private List<Long> batchGet(List<Result> resultList) {
		if (CollectionUtils.isEmpty(resultList)) {
			throw new LeafServerException("获取ID列表异常，请重新刷新");
		}
		List<Long> idsList = resultList.stream().map(result -> {
			return get(result);
		}).collect(Collectors.toList());

		return idsList;

	}
}
